package com.ysxsoft.wdg.ui.fragment.order;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ViewUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.center_st.StOrderAdapter;
import com.ysxsoft.wdg.adapter.home.TbkAdapter;
import com.ysxsoft.wdg.adapter.order.OnOrderClickListener;
import com.ysxsoft.wdg.adapter.order.ZyOrderDetailActivity;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.ZyOrderBean;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.HomeProductResponse;
import com.ysxsoft.wdg.bean.response.StOrderResponse;
import com.ysxsoft.wdg.bean.response.StPayResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayPopWindow2;
import com.ysxsoft.wdg.pay.PayPopWindowWithCoupon;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.my.CouponListActivity;
import com.ysxsoft.wdg.ui.activity.order.AplyBackOrderActivity;
import com.ysxsoft.wdg.ui.activity.order.BackOrderDetailActivity;
import com.ysxsoft.wdg.ui.activity.order.EmsActivity;
import com.ysxsoft.wdg.ui.activity.order.StOrderStatusDetailActivity;
import com.ysxsoft.wdg.ui.activity.order.ZyOrderPlActivity;
import com.ysxsoft.wdg.util.BigDecimalUtil;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ListObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.transform.FastSpeedLinearLayoutManager;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class OrderStFragment extends BaseFragment implements PayResultListener,ListObserverMap.IListDataChangeObserver {

    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.tv_fk)
    TextView tvFk;
    @BindView(R.id.tv_use)
    TextView tvUse;
    @BindView(R.id.tv_Pj)
    TextView tvPj;
    @BindView(R.id.p)
    LinearLayout parent;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private TextView[] textViews;
    StOrderAdapter adapter;
    private int clickPosition;

    @Override
    protected int getLayoutId() {
        return R.layout.fm_order_st;
    }

    @Override
    protected void initData() {
        textViews = new TextView[]{tvAll, tvFk, tvUse, tvPj};
        setSelector(0);

        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        recyclerview.setLayoutManager(new FastSpeedLinearLayoutManager(getContext()));
        adapter = new StOrderAdapter(new ArrayList<>(), getActivity());
        recyclerview.setAdapter(adapter);

        getList();
        ListObserverMap.reg("OrderStFragment",this);

    }

    @Override
    public void onResume() {
        super.onResume();
        page=1;
        getList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ListObserverMap.remove("OrderStFragment");
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getList();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                getList();
            }
        });

        adapter.setOnOrderClickListener(new OnOrderClickListener() {
            @Override
            public void OnLeftClickListener(int type, int position) {
                clickPosition = position;
                if (datas.size() < position) {
                    return;
                }
                StOrderResponse.DataBean order = datas.get(position);
                switch (type) {  //0未付1待使用2待评价
                    case 0://取消订单
                        cancelOrder("" + order.getOrderid());
                        break;
                    case 1://退款
                        AplyBackOrderActivity.start(getActivity(), "" + order.getOrderid(), 2);
                        break;
                }
            }

            @Override
            public void OnRightClickListener(int type, int position) {
                clickPosition = position;
                StOrderResponse.DataBean order = datas.get(position);
                switch (type) {//0未付1已付，待发货2已发货，待收货3已收货，待评价4完成5退款售后6退款成功
                    case 0://立即支付
                        showPayWindow(order.getAccount(), order.getOrderid() + "", order.getCompanyid() + "");
                        break;
                    case 1://立即使用
//                        notifyOrder(order.getId() + "");
                        StOrderStatusDetailActivity.start(getActivity(),order.getOrderid()+"");
                        break;
                    case 2://立即评价
                        List<StOrderResponse.DataBean.DetailBean> products=new ArrayList<>();
                        if(products!=null&&products.size()>0){
                            StOrderResponse.DataBean.DetailBean p=products.get(0);
                            ZyOrderPlActivity.start(getActivity(), order.getCompanyid() + "",p.getProductid()+"",order.getOrderid()+"", 1);
                        }
                        break;
                }
            }

            @Override
            public void OnItemClickListener(int position) {
                int status=datas.get(position).getStatus();
                if(5==status){
                    BackOrderDetailActivity.start(mContext, ""+datas.get(position).getOrderid(),true);
                }
            }
        });
    }

    @OnClick({R.id.tv_all, R.id.tv_fk, R.id.tv_use, R.id.tv_Pj})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all:
                setSelector(0);
//               	0待付款1待使用2待评价3全部
                type = 3;
                break;
            case R.id.tv_fk:
                setSelector(1);
                type = 0;
                break;
            case R.id.tv_use:
                setSelector(2);
                type = 1;
                break;
            case R.id.tv_Pj:
                setSelector(3);
                type = 2;
                break;
        }
        page = 1;
        getList();
    }

    private int type = 3;

    public void setSelector(int position) {
        for (int i = 0; i < textViews.length; i++) {
            if (position == i) {
                textViews[i].setSelected(true);
            } else {
                textViews[i].setSelected(false);
            }
        }
    }

    private int page = 1;
    List<StOrderResponse.DataBean> datas = new ArrayList<>();

    /**
     * 获取精选
     */
    private void getList() {
        OkHttpUtils.post()
                .url(UrlHost.ST_ORDER)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("page", page + "")
                .addParams("status", type + "")//	0待付款1待使用2待评价3全部
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    multStatusView.showError();
                    reset();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                reset();
                if (response != null) {
                    StOrderResponse stOrderResponse = JsonUtils.parseByGson(response, StOrderResponse.class);
                    if (stOrderResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stOrderResponse.getCode())) {
                        List<StOrderResponse.DataBean> list = stOrderResponse.getData();
                        if (list != null && !list.isEmpty()) {
                            if (page == 1) {
                                datas.clear();
                                multStatusView.showContent();
                            }
                            datas.addAll(list);
                        } else {
                            if (page == 1) {
                                multStatusView.showEmpty();
                            }
                        }
                        adapter.setData(list);
                    } else {
                        if (page == 1) {
                            multStatusView.showEmpty();
                        }
                    }
                } else {
                    multStatusView.showError();
                }
            }
        });
    }

    private void reset() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh(true);
        }
        refreshLayout.finishLoadmore();
    }

    /**
     * 取消订单
     */
    private void cancelOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.CANCEL_ORDER)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("type", "1")//1自营2实体
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
//                        adapter.notifyItemRemoved(clickPosition);
//                        adapter.notifyDataSetChanged();
                        page=1;
                        getList();
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 通知发货
     */
    private void notifyOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.NOTIFY_SHOP)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    PayPopWindowWithCoupon payPopWindow;

    private void showPayWindow(String payMoney, String orderId, String companyid) {
        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }
        payPopWindow = new PayPopWindowWithCoupon(getActivity(), payMoney);
        payPopWindow.show(parent);
        payPopWindow.setOnPayLiatener(new PayPopWindowWithCoupon.OnPayLiatener() {
            @Override
            public void payType(int payType, String totalMoney) {//payment= "3";//支付方式 1=>微信 2=>支付宝 3=>账户余额 4=>积分支付
                AlertUtils.payAlert(getActivity());
                switch (payType) {
                    case 0://余额支付
                        postPayYue(orderId, totalMoney);//totalMoney是减去优惠券的金额
                        break;
                    case 1://支付宝支付
                        postPayZfb(orderId, totalMoney);//totalMoney是减去优惠券的金额
                        break;
                    case 2://微信支付
                        postPayWx(orderId, totalMoney);//totalMoney是减去优惠券的金额
                        break;
                }
            }

            @Override
            public void onCouponClick() {
                Intent intent = new Intent(getActivity(), CouponListActivity.class);
                intent.putExtra("account", payMoney);
                intent.putExtra("companyid", companyid);
                startActivityForResult(intent, 0x01);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x01) {
            if (data != null) {
                int c = data.getIntExtra("couponId", -1);
                String price = data.getStringExtra("price");
                String limit = data.getStringExtra("limit");
                Double d = Double.valueOf(price);
                Double l = Double.valueOf(limit);

                payPopWindow.setMoney("满" + limit + "减" + price);
                payPopWindow.setPrice(d);

                quanid=""+c;
            }
        }
    }

    /**
     * 实体订单余额支付
     */
    private void postPayYue(String orderId, String total) {
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        postFormBuilder.url(UrlHost.PAY_YUE);
        postFormBuilder.addParams("uid", SharePrefUtils.getUserId());
        postFormBuilder.addParams("orderid", orderId);//订单id
        postFormBuilder.addParams("total", total);//总价格
        postFormBuilder.addParams("type", "0");//是否积分抵现，0否1是
        postFormBuilder.addParams("quanid", quanid==null?"":quanid);//优惠券id

        postFormBuilder
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    StPayResponse stPayResponse = JsonUtils.parseByGson(response, StPayResponse.class);
                    if (stPayResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stPayResponse.getCode())) {
                        ToastUtils.showToast(stPayResponse.getMs());
                        adapter.notifyItemRemoved(clickPosition);
//                        adapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showToast(stPayResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 实体订单支付宝支付
     */
    private void postPayZfb(String orderId, String total) {
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        postFormBuilder.url(UrlHost.PAY_ALIPAY);
        postFormBuilder.addParams("uid", SharePrefUtils.getUserId());
        postFormBuilder.addParams("orderid", orderId);//订单id
        postFormBuilder.addParams("total", total);//总价格
        postFormBuilder.addParams("type", "0");//是否积分抵现，0否1是
            postFormBuilder.addParams("quanid", quanid==null?"":quanid);//优惠券id

        postFormBuilder.tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    StPayResponse stPayResponse = JsonUtils.parseByGson(response, StPayResponse.class);
                    if (stPayResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stPayResponse.getCode())) {
                        PayUtils.getInstance(mContext).pay(getActivity(), PayUtils.PAY_TYPE_ALI, stPayResponse.getData(), null);
                    } else {
                        ToastUtils.showToast(stPayResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /***
     * 实体订单微信支付
     */
    private void postPayWx(String orderId,String totalPrice) {
        if(quanid==null){
            quanid="";
        }
        mApiHelper.payStWx(SharePrefUtils.getUserId(), orderId, totalPrice,quanid, new Observer<BaseBean<WxPayBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<WxPayBean> baseBean) {
                AlertUtils.dismissAlert();
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayUtils.getInstance(mContext).toWxPay(baseBean.getData());
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                AlertUtils.dismissAlert();
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private String quanid;

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功！");
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败！");
    }

    @Override
    public void onPayCancel() {
        ToastUtils.showToast("支付取消！");
    }

    @Override
    public void ping() {
        //自营商品评论成功
        if(datas!=null&&datas.size()>clickPosition){
            datas.get(clickPosition).setDiscuss("1");
            adapter.notifyItemChanged(clickPosition);
        }
    }

    @Override
    public void pay() {
        //详情支付成功
        if(datas!=null&&datas.size()>clickPosition){
            adapter.notifyItemRemoved(clickPosition);
        }
    }

    @Override
    public void cancel() {
        page=1;
        getList();
    }
}
